package cn.tedu.zx.order.adapter.serviceImpl;

import cn.tedu.zx.common.exception.ServiceException;
import cn.tedu.zx.common.restful.ResponseCode;
import cn.tedu.zx.order.adapter.paidEnum.OrderStatus;
import cn.tedu.zx.order.adapter.mapper.OrderMapper;
import cn.tedu.zx.order.service.BookingService;
import cn.tedu.zx.pojo.order.dto.BookingAddNewDto;
import cn.tedu.zx.pojo.order.dto.BookingPrepareDto;
import cn.tedu.zx.pojo.order.dto.BookingUpdateDto;
import cn.tedu.zx.pojo.order.entity.Booking;
import cn.tedu.zx.pojo.order.vo.BookingDetailsVO;
import cn.tedu.zx.pojo.order.vo.BookingListVO;
import cn.tedu.zx.pojo.order.vo.UserBookingListVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@DubboService
@Service
@Slf4j
public class OrderServiceImpl implements BookingService {
    @Autowired
    private OrderMapper orderMapper;

    private String message;
    private int rows;

    @Override
    public void addNew(BookingAddNewDto bookingAddNewDto) {
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String now = formatter.format(dateTime);

        Date date = bookingAddNewDto.getDate();
        String time = bookingAddNewDto.getTime();
        time= dateConvoter(date, time);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = format.parse(now);
            date2 = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int compare = date1.compareTo(date2);
        if (compare >0) {
            throw new ServiceException(ResponseCode.NOT_FOUND, "预定时间已过，请重新选择时间段");
        }

        QueryWrapper<Booking> bookingQuery = new QueryWrapper<>();
        bookingQuery.eq("date", bookingAddNewDto.getDate())
                .eq("time", bookingAddNewDto.getTime())
                .eq("category_id", bookingAddNewDto.getCategoryId())
                .eq("court_id", bookingAddNewDto.getCourtId());
        Integer count = orderMapper.selectCount(bookingQuery);
        if (count > 0) {
            message = "添加失败，数据已存在";
            log.warn(message);
            throw new ServiceException(ResponseCode.CONFLICT, message);
        }
        // TODO 执行付款流程

        Booking booking = new Booking();
        BeanUtils.copyProperties(bookingAddNewDto, booking);
        booking.setCreated(LocalDateTime.now())
                .setUpdated(LocalDateTime.now())
                .setOrderTime(LocalDateTime.now())
                .setPaymentTime(LocalDateTime.now())
                .setPaymentMethod("支付宝支付")
                .setStatus(OrderStatus.PAID.getValue());
        rows = orderMapper.insert(booking);
        operateFailed(rows);
        log.debug("添加完成");

    }

    @Override
    public void deleteById(Long id) {
        BookingDetailsVO detailsVO = orderMapper.selectDetails(id);
        if (detailsVO == null) {
            message = "数据不存在";
            log.warn(message);
            throw new ServiceException(ResponseCode.NOT_FOUND, message);
        }
        rows = orderMapper.deleteById(id);
        operateFailed(rows);
        log.debug("删除完成");
    }

    @Override
    public void update(BookingUpdateDto bookingUpdateDto) {
        Booking booking = new Booking();
        BeanUtils.copyProperties(bookingUpdateDto, booking);
        booking.setUpdated(LocalDateTime.now());
        rows = orderMapper.updateById(booking);
        operateFailed(rows);
        log.debug("修改完成");
    }

    @Override
    public List<BookingListVO> list() {
        List<BookingListVO> list = orderMapper.list();
        if (list == null) {
            message = "数据不存在";
            log.warn(message);
            throw new ServiceException(ResponseCode.NOT_FOUND, message);
        }
        log.trace("列表查询完成");
        return list;
    }

    @Override
    public List<Booking> dateList() {
        List<Booking> list = orderMapper.dateList();
        if (list == null) {
            message = "数据不存在";
            log.warn(message);
            throw new ServiceException(ResponseCode.NOT_FOUND, message);
        }
        log.trace("列表查询完成");
        return list;
    }

    @Override
    public BookingDetailsVO selectDetails(Long id) {
        BookingDetailsVO bookingDetailsVO = orderMapper.selectDetails(id);
        if (bookingDetailsVO == null) {
            message = "数据不存在";
            log.warn(message);
            throw new ServiceException(ResponseCode.NOT_FOUND, message);
        }
        log.trace("详情查询完成");
        return bookingDetailsVO;
    }

    private void operateFailed(Integer operateRows) {
        if (operateRows < 1) {
            message = "服务器异常，请稍后再试";
            log.warn(message);
            throw new ServiceException(ResponseCode.INTERNAL_SERVER_ERROR, message);
        }
    }

    @Override
    public List<BookingPrepareDto> prepareList(String date, Long categoryId) {
        System.out.println(date);
        List<BookingPrepareDto> list = orderMapper.prepareList(date, categoryId);
        return list;
    }

    @Override
    public List<UserBookingListVO> listByUserId(Long userId) {
        List<UserBookingListVO> listByUser = orderMapper.listByUserId(userId);
        if (listByUser == null) {
            message = "数据不存在";
            throw new ServiceException(ResponseCode.NOT_FOUND, message);
        }
        return listByUser;
    }

    @Override
    public void deleteByUserId(Long id) {
        orderMapper.deleteByUserId(id);
    }

    /**
     * 订单生效
     */
    @Override
    public void setFinish() {
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String now = formatter.format(dateTime);

        List<Booking> list = orderMapper.dateList();
        for (Booking booking : list) {
            Date date = booking.getDate();
            String time = booking.getTime();
            time = dateConvoter(date, time);
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date1 = null;
            Date date2 = null;
            try {
                date1 = format.parse(now);
                date2 = format.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            int compare = date1.compareTo(date2);
            if (compare >= 0) {
                booking.setStatus(OrderStatus.FINISH.getValue());
                orderMapper.updateById(booking);
            }
        }
    }

    /**
     * 取消订单
     */
    @Override
    public void setCancel(Long id) {
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(30);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String now = formatter.format(dateTime);

        BookingDetailsVO bookingDetailsVO = orderMapper.selectDetails(id);
        Date date = bookingDetailsVO.getDate();
        String time = bookingDetailsVO.getTime();
        time= dateConvoter(date, time);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = format.parse(now);
            date2 = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int compare = date1.compareTo(date2);
        if (compare < 0) {
            bookingDetailsVO.setStatus(OrderStatus.CANCEL.getValue());
            Booking booking = new Booking();
            BeanUtils.copyProperties(bookingDetailsVO, booking);
            orderMapper.updateById(booking);
            //TODO 执行退款流程
        } else {
            throw new ServiceException(ResponseCode.NOT_FOUND, "距离预定时间小于30分钟");
        }
    }


    private String dateConvoter(Date date,String  bookingTime){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateToString = simpleDateFormat.format(date);
        String sub =  bookingTime.substring(0, bookingTime.indexOf("-"));
        log.debug("截取时间{}",sub);
         bookingTime = dateToString+" "+sub;
        log.debug("拼接{}", bookingTime);
        return bookingTime;
    }

}
